package com.fxnotes.common.thread;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.concurrent.Worker;

public class TaskFxExecutor implements TaskExecutor {

    @Override
    public void execute(final Executable executable) {
        final Task task = new Task() {

            @Override
            protected Object call() throws Exception {
                executable.execute();
                return null;
            }
        };

        task.stateProperty().addListener(new ChangeListener<Worker.State>() {

            @Override
            public void changed(ObservableValue<? extends Worker.State> ov, Worker.State state, Worker.State newState) {
                if (newState.equals(Worker.State.SUCCEEDED)) {
                    executable.onSuccess();

                } else if (newState.equals(Worker.State.FAILED)) {
                    executable.onFail(task.getException().getMessage());
                }
            }
        });

        new Thread(task).start();
    }
}
